﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using sConfiguration;
using System.Configuration;



namespace DataAccess
{
    public static class GenericData
    {
        public static DbConnection connection;
        static GenericData()
        {

        }

        public static DataTable ExecuteReader(DbCommand command)
        {
            DataTable table = null;
            try
            {
                command.Connection.Open();
                DbDataReader reader = command.ExecuteReader();
                table = new DataTable();
                table.Load(reader);
                return table;
            }
            catch (Exception ex)
            {
                MessagesBox.Show("Error : " + ex.Message);
            }
            finally
            {
                command.Connection.Close();
            }
            return table;
            
        }

        //Create a command
        public static DbCommand CreateCommand()
        {

            string dbProviderName = sConfiguration.Configuration.DbProviderName;
            string dbConnectionString = sConfiguration.Configuration.DbConnectString;
            DbProviderFactory factory = DbProviderFactories.GetFactory(dbProviderName);
            connection = factory.CreateConnection();
            connection.ConnectionString = dbConnectionString;
            DbCommand command = connection.CreateCommand();
            command.CommandType = CommandType.Text;
            return command;

        }

        public static int ExecuteNoneQuery(DbCommand command)
        {

            int AfectedRows = -1;
            try
            {
                command.Connection.Open();
                AfectedRows = command.ExecuteNonQuery();
            }
            catch (Exception ex)
            { //throw ex; 
                MessagesBox.Show("Error : " + ex.Message);
            }

            finally
            { command.Connection.Close(); }
            return AfectedRows;
        }


        public static string ExecuteScalar(DbCommand command)
        {
            string value = "";
            try
            {
                command.Connection.Open();
                value = command.ExecuteScalar().ToString();
            }
            catch (Exception ex)
            {
                MessagesBox.Show("Error : " + ex.Message);
            }
            finally
            { command.Connection.Close(); }
            return value;
        }

        
    }

    
}